<template>
  <div class="login">
    <p class="title_p">
      <span>{{ t('home_page_login') }}</span>
      <iconpark-icon class="close" icon-id="exit" color="#fff" size="1rem" @click="onClose"></iconpark-icon>
    </p>
    <div class="content">
      <div class="tab">
        <span v-shrink-on-click :class="state.active == i ? 'active_tab' : ''" v-for="(tab, i) in tabList" :key="i"
          @click="changeTab(i)">{{
            t(tab.name) }}</span>
      </div>

      <div class="reg-box">

        <nut-form ref="formRef" label-position="top" :model-value="state.login" :rules="state.loginRules">
          <template v-for="(item, i) in state.loginList ">
            <nut-form-item :label="t(item.label)" v-if="item.show" :rules="state.loginRules[item.name]"
              :prop="item.name" :key="i">
              <nut-input v-model="state.login[item.name]" :placeholder="t(item.placeholder)" :type="item.type"
                @blur="blurValidate(item.name)" clearable>
                <!-- <template #left v-if="item.leftIcon">
                  <iconpark-icon :icon-id="item.leftIcon" color="#fff" size="1.5rem"></iconpark-icon>
                  <span v-if="item.name == 'cellphone'" style="color:#fff;margin-left: 5px;">+{{ state.codeValue
                    }}</span>
                </template> -->
                <template #right>
                  <span @click="iconClick(item)" v-if="item.changeRightIcon"
                    style="color: #8e82c2!important;font-size: 18px!important;">
                    <iconpark-icon v-if="item.type == 'password'" name="hide" color="#8e82c2"
                      size="1rem"></iconpark-icon>
                    <iconpark-icon v-if="item.type == 'text'" name="eye12" color="#8e82c2" size="1rem"></iconpark-icon>
                  </span>
                </template>

                <template v-if="item.name == 'captcha'" #right>
                  <div @click="refresh_captcha" class="btn">

                    <ImgT v-shrink-on-click :src="state.captchaURL" v-if="state.captchaURL && !state.captchaLoading"
                      alt="captchaURL" />
                    <ImgT :class="{ 'loading_icon': state.captchaLoading }" v-if="state.captchaLoading"
                      style="width:20px;height:20px" :src="'/imgs/level/level_icon_re.webp'" />

                  </div>
                </template>
              </nut-input>
            </nut-form-item>
          </template>

        </nut-form>
      </div>

      <div @click="checked = !checked"
        style="display: flex;align-items: center;justify-content: flex-start;color: #fff;font-size: 12px;font-weight: 400;position: relative;top:-5px;cursor: pointer;">
        <img v-if="checked" style="width:14px;height:14px;margin-right:4px" src="/imgs/login/checked.webp" alt="">
        <img v-if="!checked" style="width:14px;height:14px;margin-right:4px" src="/imgs/login/uncheck.webp" alt="">
        <span>{{ t('home_page_rememberPassword') }}</span>
      </div>

      <div>
        <nut-button class="btn_block" :style="{ 'opacity': state.loading ? '0.5' : 1 }" round block
          @click="onLoginSubmit">
          {{ t("home_page_login") }}
        </nut-button>
      </div>
      <p class="set_password">
        <i @click="openReg">{{ t('home_page_noAccount') }}</i>
        <i @click="openForget">{{ t('home_page_forgetPassword') }}</i>
      </p>

    </div>

  </div>
  <!-- </div> -->
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from "vue";
// import { Net } from "@/net/Net";
import H5Websocket from "@/net/Net1";
import { NetPacket } from "@/netBase/NetPacket";


import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { verifyAccount, verifyCaptcha, verifyEmail, verifyMobile, verifyPassword } from "../utils/validateTools";
import { aaa, bbb, device_model, getDeviceId, getRandomSign } from "../net/Utils";

import { MessageEvent2 } from "../net/MessageEvent2";
import { NetMsgType } from "@/netBase/NetMsgType";
import { showNotify } from '@nutui/nutui'
import { User } from "../store/user";
import pinia from '@/store/index';
import { needLoginApi } from "@/utils/useNetMethods";
import { IP } from "@/utils/useStoreMethods";
import { Local } from '@/utils/storage';

const { t } = useI18n();
const checked = ref(true) // 记住密码

const router = useRouter();
const formRef = ref()
const route = useRoute();
const state: any = reactive({
  captchaURL: '',
  loading: false,
  captchaLoading: false,
  active: 0,
  formInitValue: null,
  rememberPassword: true,
  loginList: {
    phone: {
      name: "phone",
      label: 'home_page_phone',
      type: "text",
      placeholder: 'home_page_phone', //'home_page_enterPhoneNumber',
      slot: !1,
      leftIcon: false,
      changeRightIcon: !1 as any,
      show: !1,
      isPhone: true
    },
    account: {
      name: "account",
      label: 'home_page_account',
      type: "text",
      placeholder: 'home_page_account', //'home_page_enterAccount',
      slot: !1,
      leftIcon: "signicon01",
      changeRightIcon: !1 as any,
      show: true,
      // filterable: true,
      // options: [
      //   {
      //     label: 'Drive My Car',
      //     value: 'song1'
      //   },
      //   {
      //     label: 'Norwegian Wood',
      //     value: 'song2'
      //   },
      //   {
      //     label: "You Won't See",
      //     value: 'song3',

      //   },
      // ]
    },
    email: {
      name: "email",
      label: 'home_page_email',
      type: "text",
      placeholder: 'home_page_email', //'home_page_enterEmail',
      slot: !1,
      leftIcon: "signicon05",
      changeRightIcon: !1 as any,
      show: false,
    },
    password: {
      name: "password",
      label: 'home_page_password',
      type: "password",
      placeholder: 'home_page_password', //'home_page_enterPassword',
      slot: !0,
      leftIcon: "signicon02",
      changeRightIcon: "hide" as any,
      show: !0,
    },
    captcha: {
      name: "captcha",
      label: 'home_page_verificationCode',
      type: "text",
      placeholder: 'home_page_verificationCode', // 'home_page_enterVerificationCode',
      slot: !0,
      leftIcon: "signicon03",
      changeRightIcon: !1 as any,
      show: !0,
    },
  },

  login: {
    captcha: "",
    userName: '',
    phone: '',
    account: '',
    email: '',
    password: '',
  },
  loginRules: {
    phone: [
      {

        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t('home_page_enterPhoneNumber'))
          } else
            if (verifyMobile(state.codeValue, value)) {
              return Promise.resolve()
            } else {
              return Promise.reject(t('home_page_phoneNumberFormatIncorrect'))
            }

        },
      }
    ],
    captcha: [
      {

        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t('home_page_enterVerificationCode'))
          } else
            if (verifyCaptcha(value)) {
              return Promise.resolve()
            } else {
              return Promise.reject(t('home_page_verificationCodeFormatIncorrect'))
            }
        },

      },
    ],
    email: [
      {

        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t('home_page_enterEmail'))
          } else if (verifyEmail(value)) {
            return Promise.resolve()
          } else {
            return Promise.reject(t('home_page_emailIncorrect'))
          }
        },
      }
    ],
    password: [
      {

        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t('home_page_enterPassword'))
          } else
            if (verifyPassword(value)) {
              return Promise.resolve()
            } else {
              return Promise.reject(t('home_page_passwordFormatIncorrect'))
            }
        },

      },
    ],
    account: [
      {
        trigger: "blur",
        validator: (value: string) => {
          if (!value) {
            return Promise.reject(t('home_page_enterAccount'))
          } else
            if (verifyAccount(value)) {
              return true
            } else {
              return Promise.reject(t('home_page_accountFormatIncorrect'))
            }
        },

      },
    ],
  },

  codeValue: '84',
  codeOptions: [
    // {
    //   label: '+63',
    //   value: '+63',
    // },
    {
      label: '84',
      value: '84',
    },
    // {
    //   label: '+86',
    //   value: '+86',
    // },
  ]
});
// 登录缓存
const setLocal = () => {
  if (Local.get('account') !== null || Local.get('email') !== null) {
    setTimeout(() => {
      if (state.active == 0) {
        state.login.account = Local.get('account')
        if (state.login.account) {
          state.login.password = Local.get('password')
        } else {
          state.login.password = ''
        }
      } else {
        state.login.email = Local.get('email')
        if (state.login.email) {
          state.login.password = Local.get('password')
        } else {
          state.login.password = ''
        }
      }

    }, 0)
  }
}
setLocal()
const tabList = [
  { name: 'home_page_accountLogin', value: 1 },
  { name: 'home_page_emailLogin', value: 2 }
]
const handleCaptchaReceive = (captcha: any) => {
  state.captchaLoading = false
  state.captchaURL = captcha.url;
}
const blurValidate = (prop: string) => {
  formRef.value?.validate(prop).then()
}
const refresh_captcha = async () => {
  const req_register_captcha = NetPacket.req_register_captcha();
  let id = await getDeviceId()
  req_register_captcha.sign = getRandomSign(id);;
  req_register_captcha.aaa = aaa;
  req_register_captcha.bbb = bbb;
  // Net.instance.sendRequest(req_register_captcha);
  H5Websocket.sendMessageHandler(req_register_captcha)
  state.captchaLoading = true
};
const iconClick = (a: any) => {
  if (a.type == "password") {
    a.type = "text"
  } else {
    a.type = "password"
  }
};


const changeTab = (tabId: number) => {
  state.active = tabId;
  formRef.value?.reset()
  if (state.active == 1) {

    state.loginList.account.show = false
    state.loginList.email.show = true
  } else {
    state.loginList.account.show = true
    state.loginList.email.show = false

  }
  state.login = {
    captcha: "",
    userName: '',
    phone: '',
    account: '',
    email: '',
    password: '',
  }

  // 记住密码的逻辑
  if (checked.value) {
    setLocal()
  }

};
const onLoginSubmit = async () => {
  if (state.loading) return
  formRef.value?.validate().then(async ({ valid, errors }: any) => {
    if (valid) {
      state.loading = true
      const req_login = NetPacket.req_login();
      switch (state.active) {
        case 0:
          req_login.username = state.login.account;
          req_login.login_type = 4;
          break;
        case 1:
          req_login.username = state.login.email;
          req_login.login_type = 5;
          // req_login.username = state.codeValue + state.login.phone;
          break;
      }

      req_login.password = state.login.password;
      req_login.device_id = await getDeviceId();
      req_login.device_model = device_model;
      req_login.channel_id = route.query.channel_id || 123;
      req_login.aaa = aaa;
      req_login.bbb = bbb;
      req_login.ip = await IP();
      req_login.captcha = state.login.captcha;
      // Net.instance.sendRequest(req_login);
      H5Websocket.sendMessageHandler(req_login);
    } else {
      console.warn('error:', errors)
    }
  })

};
const loginSuccess = async (message: any) => {
  state.loading = false
  setTimeout(() => {
    state.loading = false
  }, 300)

  const last_user_id = localStorage.getItem('last_user_id')
  if (last_user_id != message.user_id) {
    localStorage.setItem('readed_notice_ids', '[]')
  }
  localStorage.setItem('last_user_id', message.user_id)

  if (message.code == 4444) {
    return;
  }
  if (message.code == 1) {
    if (message.message) {
      showNotify.success(t('home_page_loginSuccess'))
    }
    if (checked.value) {
      Local.set('account', state.login.account)
      Local.set('email', state.login.email)
      Local.set('password', state.login.password)
    }
    if (!checked.value) {
      Local.remove('account')
      Local.remove('email')
      Local.remove('password')
    }
    await User(pinia).getUserLoginInfo(message)
    onClose()
    router.replace({ name: 'home' })
    needLoginApi()
  } else {
    refresh_captcha()
  }
}
const openForget = async () => {
  await User(pinia).setForget(true)
  onClose()
}
const openReg = async () => {
  await User(pinia).setLogin(false)
  setTimeout(() => {
    User(pinia).setReg(true)
  }, 300)
}
const onClose = async () => {
  await User(pinia).setLogin(false)
}
onMounted(async () => {
  MessageEvent2.addMsgEvent(
    NetMsgType.msgType.msg_notify_register_captcha,
    handleCaptchaReceive
  );
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_nodify_login, loginSuccess);

  refresh_captcha();
  // setTimeout(() => {
  //   state.loginList.password.type = 'password'
  // }, 500);

  // formRef.value?.reset()


});
onUnmounted(() => {
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_register_captcha, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_nodify_login, null);
})
</script>

<style lang="scss" scoped>
@keyframes roll {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}

.login {
  border-radius: 16px;
  background: #131232;
  box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
  width: 347px;

  .loading_icon {
    animation: roll 1s linear infinite;
  }

  :deep(.nut-input-value) {
    border-radius: 8px;
    background: #1D1C3C;
    box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
    height: 48px;
    line-height: 48px;
    padding: 0 14px;
  }


  :deep(.nut-form-item) {
    padding: 0 0 14px 0 !important;

    .nut-cell__title {
      display: none !important;
    }
  }

  :deep(.nut-cell-group__wrap) {
    box-shadow: none;
    margin: 0;
  }

  :deep(.nut-form-item__body__slots) {
    display: flex;
  }

  :deep(.nut-cell-group .nut-cell::after) {
    border: none;
  }

  :deep(.nut-form-item.error.line::before) {
    border: none;
  }

  :deep(.nut-input-right-box) {
    position: relative;
  }

  :deep(.input-text) {
    &::placeholder {
      color: #504F6F !important;
    }
  }

  .title_p {
    border-bottom: 0.5px solid #242352;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #FFF;
    font-size: 16px;
    font-weight: 500;
    line-height: 16px;
    position: relative;

    .close {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      color: #fff;
      font-size: 20px;
    }
  }

  .content {
    padding: 20px 20px 32px 20px;

    .tab {
      width: 200px;
      margin: 0 auto 20px auto;
      display: flex;
      justify-content: space-around;
      align-items: center;
      border-radius: 8px;
      background: #0B0B23;

      >span {
        width: 100px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #504F6F;
        font-size: 14px;
        font-weight: 400;
      }

      .active_tab {
        border-radius: 8px;
        background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
        box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
        color: #fff;
        font-weight: 500;
        margin: 2px;
      }
    }
  }

  .set_password {
    color: #5D69FF;
    font-size: 12px;
    line-height: 14px;
    display: flex;
    justify-content: space-between;
    margin-top: 16px;


    i {
      font-style: normal;
      cursor: pointer;
      text-decoration: underline;
    }
  }

  .btn {
    width: 131px;
    height: 44px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    align-items: center;
    border-radius: 8px !important;
    overflow: hidden;
    position: relative;
    left: 12px;
    background-color: #0F052A;

    >img {
      width: 100%;
      height: 100%;
    }
  }



  .btn_block {
    border-radius: 8px !important;
    background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
    height: 44px;
    margin-top: 10px;
  }
}
</style>